// packageK/my/my.js
const app = getApp()
var getInvite = require("../../mybehaviors/getInvite/getInvite");
const skinBehavior = require('../../utils/themeSkin/skinBehavior');
Page({
  behaviors: [getInvite,skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    canIUseGetUserProfile: false,
    canIUseGetUserProfileTap:false,
    logintap: false,
    footshow: false,
    loginshow: false,
    // 平台协议
    PlatformAgreement: '',
    openPlatformAgreement: false,
    tapSelectAgreement: true,
    agreement_name: '平台协议',
    // 首次授权登录自动绑定手机号(PS：新会员！！！首次)
    showAutoBindPhone: false, 
    verified: false
  },

  /**
   * 跳转到申请页面
   * @param {Object} e 
   */
  toApplication: function(e) {
    var value = wx.getStorageSync("setNewDecorateMember");
    if (value != 1) {
      this.setData({
        lsgow: true
      })
      return
    }
    const { appType } = e.currentTarget.dataset
    wx.navigateTo({
      url: '/packageK/application/application?appType=' + appType,
    })
  },

  firstlogin() {
    let firstlogin = false;
    try {
      var value = wx.getStorageSync("wx_token");
      if (value) {
        // Do something with return value
        this.setData({
          loginshow: false,
        });
        firstlogin = false;
      } else {
        // console.log('没登陆')
        this.setData({
          loginshow: true,
        });
        firstlogin = true;
      }
    } catch (e) {
      // Do something when catch error
    }
    return firstlogin;
  },

  // 隐藏二维码
  clicktapshow() {
    this.setData({
      isshow: false,
      lsgow: false,
    });
  },

  getUserProfileTap(e) {
    let that = this;
    if(this.data.canIUseGetUserProfileTap) return; 
    this.setData({
      canIUseGetUserProfileTap:true
    });
    if (this.data.canIUseGetUserProfile) {
      wx.getUserProfile({
        desc: '获取用户信息',
        success: function (_info) {
          let info = {
            'nickName': _info.userInfo.nickName,
            'avatarUrl': "",
            'gender': _info.userInfo.gender
          };
          that.loginbtn(info);
        },
        fail:function(e){
          console.log(e)
          that.setData({
            canIUseGetUserProfileTap:false
          });
        }
      });
    } else {
      let _info = e.detail;
      let info = {
        'nickName': _info.userInfo.nickName,
        'avatarUrl': "",
        'gender': _info.userInfo.gender
      };
      that.loginbtn(info);
    }
  },

  loginbtn(_info) {
    if (this.data.logintap) {
      // 正在请求 return
      return;
    }
    this.setData({
      logintap: true
    });
    var that = this;
    wx.showLoading({
      title: '登陆中...',
    })
    wx.login({
      success: function (_json) {
        if (_json.code) {
          // 请求登录接口
          wx.request({
            url: app.getNetAddresss("member.login.index"),
            header: {
              'Content-Type': 'application/json',
              'Accept': 'application/json',
            },
            data: {
              code: _json.code,
              info: _info,
              ver: '2'
            },
            success: function (res) {
              var _data = res.data;
              console.log("登录接口", res);
              setTimeout(() => {
                that.setData({
                  logintap: false
                });
              }, 1000);
              if (_data.result == 1) {
                // 存储key
                if (_data.data.user_info) {
                  wx.setStorageSync("nickname", _data.data.user_info.nickname);
                }
                if (_data.msg.session) {
                  wx.setStorageSync('session', _data.msg.session);
                }
                // wx.setStorage({
                // 	key: "session",
                // 	data: _data.msg.session
                // })
                wx.setStorage({
                  key: "openid",
                  data: _data.data.openid
                });
                if (_data.msg.wx_token) {
                  wx.setStorageSync('wx_token', _data.msg.wx_token);
                }
                // wx.setStorage({
                // 	key: "wx_token",
                // 	data: _data.msg.wx_token
                // })
                if (_info) {
                  wx.setStorageSync('userInfo', _info);
                }
                //that.globalData.uid = _data.msg.uid;
                wx.setStorage({
                  key: "yz_uid",
                  data: _data.msg.uid
                });
                if( _data.data.is_first_time_bind){
                  // 首次授权登录自动绑定手机号
                  that.setData({
                    showAutoBindPhone: true
                  });
                }else{
                  that.getInvite();
                }
                wx.removeStorageSync("new_decorate"); //登录之后清除首页缓存数据重新请求
              } else {
                wx.showModal({
                  title: '提示',
                  content: _data.msg,
                  success(res) {
                    console.log(res);
                  }
                });
                // wx.showToast({
                // 	title: _data.msg,
                // 	icon: 'loading',
                // 	duration: 2000,
                // 	mask: true,
                // })
                console.log("第三方登录数据错误" + res.errMsg);
              }
            },
            fail: function (res) {
              that.setData({
                logintap: false,
                canIUseGetUserProfileTap:false
              });
              console.log("第三方登录失败session、wx_token获取失败" + res.errMsg);
            }
          });
        } else {
          that.setData({
            logintap: false,
            canIUseGetUserProfileTap:false
          });
          console.log("获取用户登录态失败！" + res.errMsg);
        }
      },
      fail: function (res) {
        console.log("登录失败，请求被拒绝！获取用户登录态失败！" + res);
      },
      complete: function() {
        wx.hideLoading()
      }
    });
  },

  //是否开启邀请页面
  getInvite() {
    let urlStr = app.getNetAddresss("member.member.isValidatePage");
    app._getNetWork({
      url: urlStr,
      data: {},
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          let data = res.data;
          try {
            this.checktoInvite(data, 'my');
          } catch (e) {
            wx.reLaunch({
              url: "/packageK/my/my",
            });
          }
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      });
    }
    if (options&&options.scene) {
      let scene = decodeURIComponent(options.scene);
      if (scene) {
        var info_arr = [];
        info_arr = scene.split(",");
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split("=");
          if (chil_arr[0] == "mid") {
            app._setMid(chil_arr[1]);
          }
        }
      }
    }
    if (options&&options.mid) {
      app._setMid(options.mid);
    }
    this.setData({
      footshow: true,
    });
    wx.removeStorageSync("setNewDecorateMember");
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (this.firstlogin()) {
      this.setData({
        footshow: true,
        lsgow: true,
        verified: true
      });
      try {
        let showinfo = wx.getStorageSync("yz_basic_info");
        if (showinfo.home && showinfo.home.register_setting) {
          try {
            this.setData({
              PlatformAgreement: showinfo.home.register_setting.new_agreement ? showinfo.home.register_setting.new_agreement.replace(/<img/g, '<img style="width:100%;display:flex;"') : '',
              agreement_name: app._isTextEmpty(showinfo.home.register_setting.agreement_name) ? this.data.agreement_name : showinfo.home.register_setting.agreement_name,
            });
          } catch (error) {
            console.log(error);
          }

          let shopName = showinfo.home.mailInfo.name;
          if (app._isTextEmpty(showinfo.home.register_setting.title1)) {
            showinfo.home.register_setting.title1 = `欢迎来到${shopName}`;
          }
          if (app._isTextEmpty(showinfo.home.register_setting.title2)) {
            showinfo.home.register_setting.title2 = "登录尽享各种优惠权益！";
          }
          this.setData({
            showinfo: showinfo.home.register_setting,
          });
        } else {
          this.setData({
            showinfo: {
              title1: "欢迎来到",
              title2: "登录尽享各种优惠权益！"
            }
          });
        }

      } catch (err) {
        console.log(err);
      }
    } else {
      // setNewDecorateMember是否已经请求会员数据
      var value = wx.getStorageSync("setNewDecorateMember");
      if (value != 1) {
        this.getMemberData();
        wx.setStorageSync("setNewDecorateMember", "1");
      }
    }
  },

  getMemberData() {
    console.log(app.globalData.store_alone_temp)
    if (app.globalData.store_alone_temp == 1) {
      // 开启门店独立模块
      this.getStoreMember();
      return;
    }

    let that = this;
    let urlStr = app.getNetAddresss("member.member.member-data");
    app._getNetWork({
      url: urlStr,
      data: {
        v: 2,
        basic_info:1
      },
      success: (resdata) => {
        var res = resdata.data;
        console.log(res)
        if (res.result === 1) {
          if (res.data.designer.data.page_plugins === "decorate") {
            // that.getNewDecorate(res.data.designer.data);
            that.setData({
              designerStatus: res.data.designer.status,
            });
          } else {
            if (that.data.isMCreated == 0) {
              // that.data.isMCreated 是否第一次渲染
              that.newTemplate(res.data.designer);
            }
          }

          // console.log(res.data.plugins, '开启的插件');
          // that._getMemberInfo(res.data);
          wx.stopPullDownRefresh();
          if (res.data.plugins_data && (!this.data.plugins_data.nav || this.data.plugins_data.nav.length <= 0)) {
            that.setData({
              plugins_data: res.data.plugins_data,
            });

            if (this.data.plugins_data.nav.length > 0) {
              this.setData({
                plugin_active: this.data.plugins_data.nav[0].code
              });

              if (this.data.plugin_active === 'recommend_goods') {
                that.setData({
                  ["goodsData.list"]: this.data.plugins_data.data
                });
              } else if (this.data.plugin_active === 'limitBuy_goods') {
                this.setData({
                  ["limitData.list"]: this.data.plugins_data.data,
                });
              } else {
                this.handlePlugin({
                  name: this.data.plugin_active
                });
              }
            }
          }
          const { mc_business_id, mc_merchants_id, mc_supplier_id, is_platform} = res.data.member
          if (mc_business_id) {
            wx.redirectTo({
              url: '/packageK/business/index/index',
            })
          } else if(mc_merchants_id) {
            wx.redirectTo({
              url: '/packageK/merchants/merchants',
            })
          } else if(mc_supplier_id) {
            wx.redirectTo({
              url: '/packageK/supplier/supplier',
            })
          } else if (is_platform == 1) {
            wx.redirectTo({
              url: '/packageK/platform/platform',
            })
          } else {
            this.setData({
              verified: true
            })
          }
          // if (res.data.service) {
          //   if (typeof (res.data.service) !== 'string') {
          //     that.setData({
          //       service: res.data.service
          //     });

          //     if (res.data.service.customer_open == "0") {
          //       that.setData({
          //         service: false
          //       });
          //     }
          //   }
          // }

          // if(!app._isTextEmpty(res.data.member)){
          //   this.setData({
          //     cat_adv_url:res.data.member.small_cat_adv_url
          //   })
            // if(res.data.member.member_team){
            //   this.setData({
            //     member_team:res.data.member.member_team
            //   })
            // }
          // }
          // if (!app._isTextEmpty(res.data.member.yz_member)) {
            // that.data.custom_value = res.data.member.yz_member.custom_value;
            // that.getMemberCustom(
            //   that.data.custom_value,
            //   res.data.member.yz_member.validity,
            //   res.data.setting.custom
            // ); //获取自定义数据
          // }
          // that._getEnablePlugin(res.data.plugins);
          // that._getStroeWithdraw(res.data.plugins.is_open);
          // that._getExtension(res.data.relation);
          // that._getMemberGrade(res.data.setting.level);
          // that.setData({
          //   show_member_id: res.data.setting.show_member_id,
          //   designerReadly: true,
          // });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
          });
          this.setData({
            verified: true
          })
        }
        that.setData({
          firstshow: true,
        });
      },
      fail: function (res) {
        console.log(res);
        this.setData({
          verified: true
        })
      },
    });
  },

  // getNewDecorate(data){},

  // _getMemberInfo(memberInfo) {},

  // getMemberCustom(value, validity, data) {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.getMemberData();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})